$(() => {
  //获取文章类别
  getCategory();

  function getCategoryById(id) {
    $.ajax({
      url: '/my/article/cates/' + id,
      success(res) {
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        $('#editForm [name="alias"]').val(res.data.alias);
        $('#editForm [name="name"]')
          .val(res.data.name)
          .parents('#editForm')
          .attr('data-id', res.data.Id);
      },
    });
  }
  //添加文章类别
  //弹出框
  $('.addAtc').click(function () {
    add_id = layer.open({
      type: 1,
      title: '添加文章类别',
      area: ['500px', '250px'],
      content: $('#add').html(),
    });
  });
  //提交新类别的ajax请求
  $('body').on('submit', '#addForm', function (e) {
    e.preventDefault();
    let id = $(this).parents('tr').attr('data-id');
    let item = $(this).serialize();
    $.ajax({
      type: 'POST',
      url: '/my/article/addcates',
      data: item,
      success(res) {
        if (res.status === 0) {
          layer.msg(res.message);
          layer.close(add_id);
          getCategory();
        } else layer.msg(res.message);
      },
    });
  });

  //删除类别
  $('tbody').on('click', '.delete', function () {
    let id = $(this).parents('tr').attr('data-id');
    layer.confirm(
      '您确定要删除此类别吗?',
      { icon: 3, title: '删除类别' },
      function (index) {
        layer.close(index);
        $.ajax({
          url: '/my/article/deletecate/' + id,
          success(res) {
            if (res.status === 0) {
              layer.msg(res.message);
              getCategory();
            } else {
              layer.msg(res.message);
            }
          },
        });
      }
    );
  });

  //编辑分类数据
  $('tbody').on('click', '.editBtn', function () {
    let id = $(this).parents('tr').attr('data-id');
    edit_id = layer.open({
      type: 1,
      title: '编辑文章类别',
      area: ['500px', '250px'],
      content: $('#editScr').html(),
    });
    getCategoryById(id);
  });

  //更新修改的数据
  $('body').on('submit', '#editForm', function (e) {
    e.preventDefault();
    let item = $(this).serializeArray();
    let id = $(this).attr('data-id');
    item.splice(0, 0, { name: 'Id', value: id });
    $.ajax({
      type: 'POST',
      url: '/my/article/updatecate',
      data: item,
      success(res) {
        if (res.status === 0) {
          layer.msg(res.message);
          layer.close(edit_id);
          getCategory();
        } else layer.msg(res.message);
      },
    });
  });
});
